<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简易聊天室</title>
    <link rel="stylesheet" href="./room-chat.css"/>
    <script src="./websocket-util.js"></script>
</head>
<body>
<div class="header">
    <h1>简易聊天室</h1>
    <div class="voice-controls">
        <span id="voiceStatus">语音状态: 关闭</span>
        <button id="toggleVoiceBtn" class="voice-btn" onclick="toggleVoiceChat()">开启语音</button>
    </div>
</div>

<div class="container">
    <div class="sidebar">
        <div class="room-controls">
            <h3>房间控制</h3>
            <input type="text" id="roomName" placeholder="输入房间名">
            <button onclick="createRoom()">创建房间</button>
            <button onclick="joinRoom()">加入房间</button>
            <div id="currentRoom">当前房间: 无</div>
        </div>
        <div class="user-list">
            <h3>在线用户</h3>
            <ul id="users">
            </ul>
        </div>
    </div>
    <div class="main-content">
        <div class="call-controls" id="callControls">
            <audio id="remoteAudio" autoplay></audio>
        </div>

        <div class="messages" id="messages">
            <div class="message">
                <span class="sender">系统:</span>
                <span class="content">欢迎来到聊天室!</span>
            </div>
            <!-- 消息将通过JavaScript动态添加 -->
        </div>
        <div class="message-input">
            <input type="text" id="messageInput" placeholder="输入消息..." disabled>
            <button onclick="sendMessage()" id="sendButton" disabled>发送</button>
        </div>
    </div>
</div>

<script>
    // 当前房间和用户名
    let currentRoom = null;
    let username = prompt("请输入您的用户名:") || "匿名用户";
    let isVoiceEnabled = false;
    let localStream = null;
    let currentCall = null;
    // 模拟用户列表数据
    const mockUsers = [
        {
            "name": "里斯",
            "id": "2312"
        },
        {
            "name": "里斯2",
            "id": "2312"
        }
    ];
    //websocket工具类
    let wxUtil = null;
    let userId = generateUserId();

    // 生成随机用户ID
    function generateUserId() {
        return Math.random().toString(36).substring(2, 10);
    }

    // 创建房间
    function createRoom() {
        const roomName = document.getElementById('roomName').value.trim();
        if (!roomName) {
            alert("请输入房间名");
            return;
        }

        currentRoom = roomName;
        document.getElementById('currentRoom').textContent = `当前房间: ${roomName}`;
        document.getElementById('messageInput').disabled = false;
        document.getElementById('sendButton').disabled = false;

        // 清空消息列表
        document.getElementById('messages').innerHTML = '';
        addSystemMessage(`您已创建并加入房间: ${roomName}`);
        // 在实际应用中，这里应该发送请求到服务器创建房间
        wxUtil = new WebSocketUtil('ws://localhost:40600/ws', {
            heartbeatInterval: 5000,
            onOpen: () => {
                wxUtil.sendBindMessage(roomName);
                key = roomName + "==" + username;
                mes = {
                    type: 'regist',
                    username: username,
                    userId: userId
                }
                wxUtil.sendMessage(key, mes)
            }
        });

        // 处理收到的信令消息
        wxUtil.addMessageHandler((data) => {
            switch (data.type) {
                case 'regist':
                    console.log(data);
                    break
                case 'msg':
                    addMessage(data.username, data.msg);
                    break
            }
        });

    }

    // 加入房间
    function joinRoom() {
        const roomName = document.getElementById('roomName').value.trim();
        if (!roomName) {
            alert("请输入房间名");
            return;
        }
        currentRoom = roomName;
        document.getElementById('currentRoom').textContent = `当前房间: ${roomName}`;
        document.getElementById('messageInput').disabled = false;
        document.getElementById('sendButton').disabled = false;

        // 清空消息列表
        document.getElementById('messages').innerHTML = '';
        addSystemMessage(`您已加入房间: ${roomName}`);

        // 在实际应用中，这里应该发送请求到服务器创建房间
        wxUtil = new WebSocketUtil('ws://localhost:40600/ws', {
            heartbeatInterval: 5000,
            onOpen: () => {
                wxUtil.sendBindMessage(roomName);
                key = roomName + "==" + username;
                mes = {
                    type: 'regist',
                    username: username,
                    userId: userId
                }
                wxUtil.sendMessage(key, mes)
            }
        });

        // 处理收到的信令消息
        wxUtil.addMessageHandler((data) => {
            console.log(data);
            switch (data.type) {
                case 'regist':
                    console.log(data);
                    break
                case 'msg':
                    addMessage(data.username, data.msg);
                    break
            }
        });


        // 在实际应用中，这里应该发送请求到服务器加入房间
    }

    // 发送消息
    function sendMessage() {
        const messageInput = document.getElementById('messageInput');
        const message = messageInput.value.trim();

        if (!message) return;
        if (!currentRoom) {
            alert("请先加入或创建一个房间");
            return;
        }
        // 添加消息到聊天窗口
        //addMessage(username, message);
        mes = {
            type: 'msg',
            userId: userId,
            username: username,
            msg: message
        }
        wxUtil.sendMessage(currentRoom, mes)

        // 在实际应用中，这里应该发送消息到服务器
        // 清空输入框
        messageInput.value = '';
    }

    // 添加系统消息
    function addSystemMessage(content) {
        const messagesDiv = document.getElementById('messages');
        const messageElement = document.createElement('div');
        messageElement.className = 'message';
        messageElement.innerHTML = `<span class="sender">系统:</span> <span class="content">${content}</span>`;
        messagesDiv.appendChild(messageElement);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    // 添加用户消息
    function addMessage(sender, content) {
        const messagesDiv = document.getElementById('messages');
        const messageElement = document.createElement('div');
        messageElement.className = 'message';
        messageElement.innerHTML = `<span class="sender">${sender}:</span> <span class="content">${content}</span>`;
        messagesDiv.appendChild(messageElement);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    // 更新用户列表
    function updateUserList(users) {
        const usersList = document.getElementById('users');
        usersList.innerHTML = '';

        users.forEach(user => {
            const li = document.createElement('li');
            li.innerHTML = `
                    <span>${user.name}</span>
                    <button onclick="callUser('${user.id}')" ${!isVoiceEnabled ? 'disabled' : ''}>呼叫</button>
                `;
            usersList.appendChild(li);
        });
    }

    // 切换语音聊天状态
    function toggleVoiceChat() {
        isVoiceEnabled = !isVoiceEnabled;
        const voiceBtn = document.getElementById('toggleVoiceBtn');
        const voiceStatus = document.getElementById('voiceStatus');

        if (isVoiceEnabled) {
            voiceBtn.textContent = '关闭语音';
            voiceBtn.classList.add('active');
            voiceStatus.textContent = '语音状态: 开启';
            document.getElementById('callControls').style.display = 'block';
            initializeVoiceChat();
        } else {
            voiceBtn.textContent = '开启语音';
            voiceBtn.classList.remove('active');
            voiceStatus.textContent = '语音状态: 关闭';
            document.getElementById('callControls').style.display = 'none';
            endCall();
        }

        // 更新用户列表中的呼叫按钮状态
        updateUserList(mockUsers);
    }

    // 初始化语音聊天
    async function initializeVoiceChat() {
        try {
            localStream = await navigator.mediaDevices.getUserMedia({audio: true, video: false});
            addSystemMessage('语音功能已启用，您可以开始通话');
        } catch (error) {
            console.error('获取媒体设备失败:', error);
            addSystemMessage('无法访问麦克风或摄像头，请检查权限设置');
            isVoiceEnabled = false;
            document.getElementById('toggleVoiceBtn').textContent = '开启语音';
            document.getElementById('toggleVoiceBtn').classList.remove('active');
            document.getElementById('voiceStatus').textContent = '语音状态: 关闭';
            document.getElementById('callControls').style.display = 'none';
        }
    }

    // 呼叫用户
    function callUser(userId) {
        if (!isVoiceEnabled) {
            alert('请先开启语音功能');
            return;
        }

        const user = mockUsers.find(u => u.id === userId);
        if (user) {
            addSystemMessage(`正在呼叫 ${user.name}...`);
            currentCall = userId;
            // 模拟呼叫过程
            setTimeout(() => {
                addSystemMessage(`${user.name} 已接听通话`);
                // 在实际应用中，这里应该建立WebRTC连接
            }, 2);
        }
    }

    // 发起通话
    function startCall() {
        if (!isVoiceEnabled) {
            alert('请先开启语音功能');
            return;
        }

        // 在实际应用中，这里应该选择要呼叫的用户
        // 这里简化为随机选择一个用户
        if (mockUsers.length > 0) {
            const randomUser = mockUsers[Math.floor(Math.random() * mockUsers.length)];
            callUser(randomUser.id);
        }
    }

    // 结束通话
    function endCall() {
        if (currentCall) {
            const user = mockUsers.find(u => u.id === currentCall);
            if (user) {
                addSystemMessage(`已结束与 ${user.name} 的通话`);
            }

            // 关闭媒体流
            if (localStream) {
                localStream.getTracks().forEach(track => track.stop());
            }
            // 重置UI
            document.getElementById('remoteAudio').srcObject = null;
            currentCall = null;

            // 重新初始化本地流
            if (isVoiceEnabled) {
                initializeVoiceChat();
            }
        }
    }

    // 初始化页面
    document.addEventListener('DOMContentLoaded', function () {
        updateUserList(mockUsers);

        // 模拟一些初始消息
        setTimeout(() => {
            addMessage('用户1', '大家好！');
            addMessage('用户2', '欢迎来到聊天室！');
        }, 1000);
    });

    // 按Enter键发送消息
    document.getElementById('messageInput').addEventListener('keypress', function (e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
</script>
</body>
</html>
